﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Net.Http;
using System.Runtime.CompilerServices;
using Windows.ApplicationModel;
using Newtonsoft.Json;
using RemoteDataSample.Models;

namespace RemoteDataSample.ViewModels
{
    public class MainViewModel : INotifyPropertyChanged
    {
        private ObservableCollection<RemoteImage> _remoteImages;
        private const string ServiceAddress = "http://localhost:10575/";
        private const string ApiEndpoint = "api/Values";

        /// <summary>
        ///     Initializes a new instance of the <see cref="T:System.Object" /> class.
        /// </summary>
        public MainViewModel()
        {
            if (DesignMode.DesignModeEnabled)
            {
                LoadDesignData();
            }
            else
            {
                LoadData();
            }
        }

        public ObservableCollection<RemoteImage> RemoteImages
        {
            get { return _remoteImages; }
            set
            {
                _remoteImages = value;
                OnPropertyChanged();
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private async void LoadData()
        {
            var httpClient = new HttpClient {MaxResponseContentBufferSize = 256000};
            httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");

            try
            {
                var response = await httpClient.GetAsync(ServiceAddress + ApiEndpoint);
                response.EnsureSuccessStatusCode();

                var responseBodyAsText = await response.Content.ReadAsStringAsync();
                var images = JsonConvert.DeserializeObject<RemoteImage[]>(responseBodyAsText);
                foreach (var remoteImage in images)
                {
                    remoteImage.PathUri = new Uri(ServiceAddress + remoteImage.Path, UriKind.Absolute);
                }
                RemoteImages = new ObservableCollection<RemoteImage>(images);
            }
            catch (HttpRequestException hre)
            {
                // handle issues!
            }
            catch (Exception ex)
            {
                // For debugging
            }
        }

        private void LoadDesignData()
        {
            RemoteImages = new ObservableCollection<RemoteImage>(new[]
            {
                new RemoteImage {Id = 1, Title = "Beach", Path = "ms-appx:///Assets/Beach.jpg", PathUri = new Uri("ms-appx:///Assets/Beach.jpg")},
                new RemoteImage {Id = 2, Title = "Coast", Path = "ms-appx:///Assets/Coast.jpg", PathUri = new Uri("ms-appx:///Assets/Coast.jpg")}
            });
        }

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}